document.addEventListener('DOMContentLoaded', () => {
    // Load saved credentials from localStorage
    const savedApiUsername = localStorage.getItem('tcfApiUsername');
    const savedApiPassword = localStorage.getItem('tcfApiPassword');
    const savedExtractionUsername = localStorage.getItem('tcfExtractionUsername');
    const savedExtractionPassword = localStorage.getItem('tcfExtractionPassword');

    if (savedApiUsername) document.getElementById('apiUsername').value = savedApiUsername;
    if (savedApiPassword) document.getElementById('apiPassword').value = savedApiPassword;
    if (savedExtractionUsername) document.getElementById('extractionUsername').value = savedExtractionUsername;
    if (savedExtractionPassword) document.getElementById('extractionPassword').value = savedExtractionPassword;
    const outputDiv = document.getElementById('output');
    const runButton = document.getElementById('runAutomation');
    const clearButton = document.getElementById('clearResults');
    const orderNumbersTextarea = document.getElementById('orderNumbers'); // 确保HTML中有这个ID
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    
    let isProcessing = false; // 添加处理状态标志
    
    // 添加状态消息的辅助函数
    function addStatusMessage(message, type = 'info') {
        const statusDiv = document.createElement('div');
        statusDiv.className = `status status-${type}`;
        statusDiv.innerHTML = message;
        outputDiv.appendChild(statusDiv);
        // 自动滚动到底部
        statusDiv.scrollIntoView({ behavior: 'smooth' });
        return statusDiv;
    }
    
    // 更新进度条
    function updateProgress(percent, show = true) {
        if (show) {
            progressContainer.style.display = 'block';
        } else {
            progressContainer.style.display = 'none';
            return;
        }
        
        progressBar.style.width = `${percent}%`;
    }
    
    // 创建数据表格
    function createDataTable(data) {
        if (!data || !data.length) return '';
        
        const table = document.createElement('table');
        table.className = 'data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        const headers = Object.keys(data[0]);
        
        headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header;
            headerRow.appendChild(th);
        });
        
        thead.appendChild(headerRow);
        table.appendChild(thead);
        
        // 创建表体
        const tbody = document.createElement('tbody');
        data.forEach(item => {
            const row = document.createElement('tr');
            headers.forEach(header => {
                const td = document.createElement('td');
                td.textContent = item[header] || '';
                row.appendChild(td);
            });
            tbody.appendChild(row);
        });
        
        table.appendChild(tbody);
        return table;
    }
    
    // 运行自动化流程
    runButton.addEventListener('click', async () => {
        const orderNumbersRaw = orderNumbersTextarea.value.trim();
        const orderNumbers = orderNumbersRaw.split(/\s+|\n+|,/).filter(n => n);
        const apiUsername = document.getElementById('apiUsername').value.trim();
        const apiPassword = document.getElementById('apiPassword').value.trim();
        const extractionUsername = document.getElementById('extractionUsername').value.trim();
        const extractionPassword = document.getElementById('extractionPassword').value.trim();

        // Save credentials to localStorage
        localStorage.setItem('tcfApiUsername', apiUsername);
        localStorage.setItem('tcfApiPassword', apiPassword);
        localStorage.setItem('tcfExtractionUsername', extractionUsername);
        localStorage.setItem('tcfExtractionPassword', extractionPassword);

        console.log('Order Numbers:', orderNumbers);

        // 清空之前的输出
        outputDiv.innerHTML = '';

        // 验证输入
        if (orderNumbers.length === 0) {
            addStatusMessage('请输入有效的单号', 'error');
            return;
        }

        // 禁用按钮，显示进度条
        runButton.disabled = true;
        updateProgress(10);

        // 添加初始状态消息
        addStatusMessage(`<strong>开始处理 ${orderNumbers.length} 个单号...</strong>`, 'info');

        try {
            // 获取用户设置
            let userSettings = {};
            try {
                userSettings = await window.electronAPI.getUserSettings();
            } catch (error) {
                console.warn('无法获取用户设置:', error);
            }
            
            // 第一阶段：数据获取
            addStatusMessage('正在连接系统并获取数据...', 'info');
            updateProgress(20);

            const result = await pluginAPI.runPluginScript({
                pluginName: 'tcf-input',
                script: 'test.js',
                args: [orderNumbers, apiUsername, apiPassword, extractionUsername, extractionPassword, userSettings]
            });
            
            console.log('Plugin script result:', result);
            
            // 检查返回结果结构
            if (!result.success) {
                throw new Error(result.error || result.message || '未知错误');
            }
            
            // 提取数据部分
            const data = result.data;
            
            // 更新进度
            updateProgress(70);
            
            // 显示获取的数据
            console.log('Extracted data:', data);
            
            // 检查数据结构
            let dataArray = data;
            
            // 处理可能的嵌套数据结构
            if (data && typeof data === 'object') {
                // 如果数据在data.data中
                if (data.data && Array.isArray(data.data)) {
                    dataArray = data.data;
                }
                // 如果数据本身就是数组
                else if (Array.isArray(data)) {
                    dataArray = data;
                }
                // 如果数据是单个对象，转换为数组
                else if (!Array.isArray(data) && typeof data === 'object' && Object.keys(data).length > 0) {
                    dataArray = [data];
                }
            }
            
            if (dataArray && Array.isArray(dataArray) && dataArray.length > 0) {
                addStatusMessage(`成功获取到 <strong>${dataArray.length}</strong> 条数据记录`, 'success');
                
                // 创建并添加数据表格
                const dataTable = createDataTable(dataArray);
                const tableContainer = document.createElement('div');
                tableContainer.appendChild(dataTable);
                outputDiv.appendChild(tableContainer);
                
                // 添加原始JSON数据（折叠状态）
                const detailsElement = document.createElement('details');
                const summaryElement = document.createElement('summary');
                summaryElement.textContent = '查看原始数据';
                detailsElement.appendChild(summaryElement);
                
                const preElement = document.createElement('pre');
                preElement.textContent = JSON.stringify(dataArray, null, 2);
                detailsElement.appendChild(preElement);
                
                outputDiv.appendChild(detailsElement);
            } else {
                console.error('数据格式不正确或为空:', data);
                addStatusMessage('未获取到任何数据，请检查单号是否正确', 'warning');
            }
            
            // 更新进度
            updateProgress(100);
            
            // 完成消息
            addStatusMessage('自动化流程已成功完成！', 'success');
            
            // 延迟后隐藏进度条
            setTimeout(() => updateProgress(0, false), 1000);
            
        } catch (error) {
            console.error('自动化过程出错:', error);
            updateProgress(0, false);
            addStatusMessage(`<strong>错误:</strong> ${error.message}`, 'error');
            
            // 添加错误详情（如果有）
            if (error.stack) {
                const detailsElement = document.createElement('details');
                const summaryElement = document.createElement('summary');
                summaryElement.textContent = '查看错误详情';
                detailsElement.appendChild(summaryElement);
                
                const preElement = document.createElement('pre');
                preElement.textContent = error.stack;
                detailsElement.appendChild(preElement);
                
                outputDiv.appendChild(detailsElement);
            }
        } finally {
            // 重新启用按钮
            runButton.disabled = false;
        }
    });
    
    // 添加快捷键功能：Shift+Enter 提交，Enter 换行
    orderNumbersTextarea.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && e.shiftKey && !runButton.disabled) {
            e.preventDefault();
            runButton.click();
        }
        // 普通回车键允许换行，不做任何处理
    });
    
    // 添加清空结果按钮功能
    clearButton.addEventListener('click', () => {
        // 清空输出区域
        outputDiv.innerHTML = '';
        // 隐藏进度条
        updateProgress(0, false);
        // 可选：清空输入框
        // orderNumbersTextarea.value = '';
    });
});